/* eslint-disable react-hooks/exhaustive-deps */
import './index.less';

import { AudioTwoTone, PhoneTwoTone, VideoCameraTwoTone, } from '@ant-design/icons';
import AgoraRTC from 'agora-rtc-sdk-ng';
import { Button, Space } from 'antd';
import Layout, { Content, Footer, Header } from 'antd/lib/layout/layout';
import Sider from 'antd/lib/layout/Sider';
import { useEffect, useState } from 'react';
import { useLocation } from 'react-router';
import { useNavigate } from 'react-router-dom';

import { getToken } from '@/request/api';
let rtc: any  = {
  // 设置本地音频轨道和视频轨道。
  localAudioTrack: null,
  localVideoTrack: null,
  client: null
};


let options: any = {
  // 传入 App ID。
  appId: 'f28f52a2b05c49aab080f8d3bddd8b58',
  // 设置用户为 host (可发流) 或 audience（仅可收流）。
  role: 'host',
};
function Index() {
  const navigate = useNavigate();
  const { state } = useLocation();
  let [voice, setVoice] = useState(state.voice);
  let [video, setVideo] = useState(state.video);
  function fetchToken(data: any) {
    return new Promise(function (resolve) {
      getToken(data).then(res => {
        const token = res.data;
        resolve(token);
      });
    });

  };

  async function startBasicCall() { 
    rtc.client = AgoraRTC.createClient({ mode: 'live', codec: 'vp8' });
    rtc.client.setClientRole(options.role);
    let token = await fetchToken(state);
    await rtc.client.join(options.appId, state.channelName, token, state.uid);

    
      v();
    // 侦听“user-published”事件，您可以从中获取一个 AgoraRTCRemoteUser 对象
 rtc.client.on('user-published', async (user: { videoTrack: any; uid: string; audioTrack: any;},   
       mediaType: string) => {
      await rtc.client.subscribe(user, mediaType);
      console.log('subscribe success');
      if (mediaType === 'video') {
        const remoteVideoTrack = user.videoTrack;
        const remotePlayerContainer = document.createElement('div');
        remotePlayerContainer.id = user.uid;
        remotePlayerContainer.textContent = '用户名' + user.uid.toString();
        remotePlayerContainer.style.width = '30%';
        remotePlayerContainer.style.height = '60%';
        remotePlayerContainer.style.margin = '20px 10px';
        remotePlayerContainer.style.float = 'left';
        document.getElementById('room-content')?.append(remotePlayerContainer);
        remoteVideoTrack.play(remotePlayerContainer);
        
      }
      if (mediaType === 'audio') {
        const remoteAudioTrack = user.audioTrack;
        remoteAudioTrack.play();
      }
      rtc.client.on('user-unpublished', async (user: { uid: string; }) => {
        const remotePlayerContainer = document.getElementById(user.uid);
        remotePlayerContainer?.remove();
      });


    });
    rtc.client.setClientRole(options.role);


    rtc.client.on('token-privilege-will-expire', async function () {
      let token = await fetchToken(state);
      await rtc.client.renewToken(token);
    });

    // 收到 token-privilege-did-expire 回调时，从服务器重新申请一个 Token，并调用 join 重新加入频道。
    rtc.client.on('token-privilege-did-expire', async function () {
      console.log('Fetching the new Token');
      let token = await fetchToken(state);
      console.log('Rejoining the channel with new Token');
      await rtc.client.join(options.appId, state.channelName, token, state.uid);
    });

  };
  async function v() {
    if (video) {
      rtc.localVideoTrack = await AgoraRTC.createCameraVideoTrack();
      await rtc.client.publish([rtc.localVideoTrack]);
      const localPlayerContainer = document.createElement('div');
      localPlayerContainer.id = state.uid;
      localPlayerContainer.textContent = '用户名' + state.uid.toString();
      localPlayerContainer.style.width = '30%';
      localPlayerContainer.style.height = '60%';
      localPlayerContainer.style.float = 'left';
      localPlayerContainer.style.margin = '20px 10px';
      document.getElementById('room-content')?.append(localPlayerContainer);
      rtc.localVideoTrack.play(localPlayerContainer);
    }
    if (voice) {
      
      rtc.localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack();
      await rtc.client.publish([rtc.localAudioTrack]);
    }
  }


  async function leaveVideo() {
    rtc.localVideoTrack.close();
    await rtc.client.unpublish(rtc.localVideoTrack);
    const playerContainer = document.getElementById(state.uid);
      playerContainer && playerContainer.remove();
  };

  async function joinVideo() {
    rtc.localVideoTrack = await AgoraRTC.createCameraVideoTrack();
    await rtc.client.publish([rtc.localVideoTrack]);
    const localPlayerContainer = document.createElement('div');
    localPlayerContainer.id = state.uid;
    localPlayerContainer.textContent = '用户名 ' + state.uid;
    localPlayerContainer.style.width = '30%';
    localPlayerContainer.style.height = '60%';
    localPlayerContainer.style.float = 'left';
    localPlayerContainer.style.margin = '20px 10px';
    document.getElementById('room-content')?.append(localPlayerContainer);
    rtc.localVideoTrack.play(localPlayerContainer);
  };

  // 断开音频
  async function leaveVoice() {
    rtc.localAudioTrack.close();
  };

  async function joinVoice() {
    rtc.localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack();
    await rtc.client.publish([rtc.localAudioTrack]);
  };

  

  // 离开频道
  async function leave() {
    if (voice) {
      rtc.localAudioTrack.close();
    }
    if (video) {
      rtc.localVideoTrack.close();
    }
    rtc.client.remoteUsers.forEach((user: any) => {
      // 销毁动态创建的 DIV 容器
      const playerContainer = document.getElementById(user.uid);
      playerContainer && playerContainer.remove();
    });
    await rtc.client.leave();
  };


  useEffect(() => {
  startBasicCall();
  }, []);

 
  return (
    <div className='room-container'>
      <Layout>
        <Layout className='room-left'>
          <Header className='room-header'>
            <p>频道名：{state.channelName}</p>
          </Header>
          <Content className='room-content' id='room-content' style={{ overflow: 'auto' }}>
    
          </Content>
          <Footer className='room-footer'>
            <Space>
              <Button size='large'
                icon={video ? <VideoCameraTwoTone /> :
                  <VideoCameraTwoTone twoToneColor='red' />}
                onClick={() => {
                  setVideo((c: any) => !c);
                  !video ? joinVideo() : leaveVideo();
                }} />
              <Button size='large' id='voice'
                icon={voice ? <AudioTwoTone /> :
                  <AudioTwoTone twoToneColor='red' />}
                onClick={() => {
                  setVoice((c: any) => !c);
                  !voice ? joinVoice() : leaveVoice();
                }} />
              <Button size='large' icon={<PhoneTwoTone twoToneColor='red' />}
                onClick={() => {
                  leave();
                  navigate('/');
                }} />
            </Space>
          </Footer>
        </Layout>
        <Sider className='room-sider'>Sider</Sider>
      </Layout>
    </div>
  );
}

export default Index;


